<template>
  <view class="mallcenter">
    <!-- 自定义状态栏 -->
    <view class="custom-status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-center">
          <text class="navbar-title">小店</text>
        </view>
      </view>
    </view>

    <!-- 主滚动区域 -->
    <scroll-view scroll-y class="main-scroll" @scrolltolower="reachBottom">
      <view class="page-content">
        <!-- 搜索框区域 -->
        <view class="search-section">
          <view class="search-container">
            <view class="search-box">
              <view class="search-icon">
                <u-icon name="search" size="32" color="#999"></u-icon>
              </view>
              <input
                  class="search-input"
                  type="text"
                  placeholder="搜索商品"
                  placeholder-style="color: #999; font-size: 28rpx;"
                  @confirm="handleSearchConfirm"
                  @input="handleSearchInput"
                  v-model="searchKeyword"
              />
              <view class="search-clear" v-if="searchKeyword" @click="handleClearSearch">
                <u-icon name="close-circle-fill" size="28" color="#ccc"></u-icon>
              </view>
            </view>
          </view>
        </view>

        <!-- 轮播图区域 -->
        <view class="banner-section">
          <swiper
              class="main-banner"
              :indicator-dots="true"
              :autoplay="true"
              :interval="4000"
              :duration="800"
              indicator-color="rgba(255,255,255,0.5)"
              indicator-active-color="#fff"
          >
            <swiper-item v-for="(banner, index) in bannerList" :key="banner.id || index">
              <image
                  :src="banner.imgUrl"
                  class="banner-img"
                  mode="aspectFill"
                  @click="onBannerClick(banner)"
              ></image>
            </swiper-item>
          </swiper>
        </view>

        <!-- 商品区域 -->
        <view class="goods-section">
          <!-- 商品标题 -->
          <view class="section-header">
            <view class="header-content">
              <view class="header-title">
                <text class="title-main">全部商品</text>
                <text class="title-sub">发现更多优质商品</text>
              </view>
            </view>
          </view>

          <!-- 商品列表 - Grid布局 -->
          <view class="goods-container">
            <view class="goods-grid" v-if="dataList.length > 0">
              <view
                  class="product-card"
                  v-for="(item, index) in dataList"
                  :key="item.id || index"
                  @click.stop="goToDetail"
                  :data-item="item"
              >
                <view class="card-image-wrapper">
                  <image
                      class="card-image"
                      :src="item.pic"
                      mode="aspectFill"
                  ></image>
                  <view class="voucher-badge" v-if="item.voucher==1">
                    <text class="badge-text">券</text>
                  </view>
                </view>

                <view class="card-content">
                  <view class="product-title">{{ item.prodName || "" }}</view>
                  <view class="product-brief" v-if="item.brief">{{ item.brief }}</view>

                  <view class="price-section">
                    <view class="current-price">
                      <text class="price-symbol">¥</text>
                      <text class="price-number">{{ formatPrice(item.price) }}</text>
                    </view>
                    <view class="sales-info" v-if="item.soldNum">
                      <text class="sales-text">{{ item.soldNum }}人购买</text>
                    </view>
                  </view>

                  <view class="card-footer">
                    <view class="seller-info" @click.stop="goToShop" :data-item="item">
                      <image
                          class="seller-avatar"
                          :src="item.shopLogo || 'https://file.casugn.com/storecompcard/temp/男_1705454811406.png'"
                          mode="aspectFill"
                      ></image>
                      <text class="seller-name">{{ item.shopName || '商家' }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-else>
              <view class="empty-icon">📦</view>
              <view class="empty-title">暂无商品</view>
              <view class="empty-desc">快去添加第一个商品吧~</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部标签栏 -->
    <!--    <shoptabbar :tabbarIndex="0"></shoptabbar>-->
  </view>
</template>

<script>
// import shoptabbar from '../components/shoptabbar/shoptabbar.vue'
import cusSearch from '@/components/cus-search/cus-search.vue'
import authMixin from '@/common/libs/authMixin.js'

export default {
  mixins: [authMixin],
  components: {
    cusSearch,
    // shoptabbar
  },
  data() {
    return {
      statusBarHeight: 0, // 状态栏高度
      searchKeyword: '', // 搜索关键词
      bannerList: [],// 轮播图数据
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      dataList: [],
    };
  },
  async created() {
    // 获取系统信息
    this.getSystemInfo()
    // 延迟认证，避免App未准备好
    setTimeout(async () => {
      try {
        const isAuth = await this.ensureAuth(false)
        if (isAuth) {
          this.getGoodsList(1)
        } else {
          console.log('认证失败，使用默认数据')
          this.getGoodsList(1) // 即使认证失败也加载商品数据
        }
      } catch (error) {
        console.error('认证过程出错:', error)
        this.getGoodsList(1) // 出错时也加载商品数据
      }
    }, 3000)
  },
  async onShow() {
    // 页面显示时重新加载数据
    this.getGoodsList(1)
    //   获取首页轮播图
    this._getMssdIndexImg()
  },
  methods: {
    //   获取首页轮播图
    _getMssdIndexImg() {
      this.$api.getMssdIndexImg({
        pageNo: 1,
        pageSize: 100,
        column: "createTime"
      }).then(res => {
        if (res.success) {
          this.bannerList = res.result.records
        }
      })
    },
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },
    // 轮播图点击事件
    onBannerClick(banner) {
      let type = banner.type
      if (type === 1 && banner.shopId) {
        //   商铺
        uni.navigateTo({
          url: `/pagesMall/myShop/shopInfo?shopId=${banner.shopId}`
        })
      } else if (type === 2 && banner.relation) {
        //   商品
        uni.navigateTo({
          url: `/pagesMall/mallCenter/mallCenterDetail?id=${banner.relation}`
        })
      } else {
        return
      }
    },
    // 搜索输入事件
    handleSearchInput: function (e) {
      this.searchKeyword = e.detail.value;
    },
    // 搜索确认事件
    handleSearchConfirm: function () {
      if (this.searchKeyword.trim()) {
        // 重置分页状态
        this.queryParams.pageNo = 1;
        this.dataList = [];
        this.queryParams.total = 0;
        this.getGoodsList(1, this.searchKeyword.trim());
      }
    },
    // 跳转商家页面
    goToShop(event) {
      const item = event.currentTarget.dataset.item
      console.log('跳转商家', item)
      if (!item || !item.shopId) {
        uni.showToast({
          title: '商家信息不完整',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pagesMall/myShop/shopInfo?shopId=${item.shopId}`
      })
    },
    // 清空搜索
    handleClearSearch: function () {
      this.searchKeyword = '';
      // 重置搜索状态，获取全部商品
      this.queryParams.pageNo = 1;
      this.dataList = [];
      this.queryParams.total = 0;
      this.getGoodsList(1, '');
    },
    // 搜索方法（兼容原有调用）
    goToSearch: function (keyword) {
      this.searchKeyword = keyword || '';
      // 重置分页状态
      this.queryParams.pageNo = 1;
      this.dataList = [];
      this.queryParams.total = 0;
      this.getGoodsList(1, keyword);
    },
    // 获取商品列表
    async getGoodsList(arg, prodName = '') {
      uni.showLoading({
        title: '加载中...'
      })

      if (arg == 1) {
        this.queryParams.pageNo = 1
        this.dataList = []
        this.queryParams.total = 0
      }

      try {
        let res = await this.$api.getGoodsList({
          pageNo: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
          status: 1,
          prodName
        })

        if (res.success) {
          console.log('商品数据:', res.result.records);
          if (arg == 1) {
            // 首次加载
            this.dataList = res.result.records
          } else {
            // 加载更多
            this.dataList = [...this.dataList, ...res.result.records]
          }
          this.queryParams.total = res.result.total
        } else {
          this.dataList = []
          this.queryParams.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }

      uni.hideLoading()
    },
    // 商品详情
    goToDetail(event) {
      const item = event.currentTarget.dataset.item
      console.log('商品详情', item)
      if (!item || !item.id) {
        uni.showToast({
          title: '商品信息不完整',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({
        url: `/pagesMall/mallCenter/mallCenterDetail?id=${item.id}&openId=${item.openId}`
      })
    },
    // 上拉加载更多
    reachBottom() {
      if (this.queryParams.pageNo * this.queryParams.pageSize >= this.queryParams.total) {
        uni.showToast({
          title: '没有更多数据了',
          icon: 'none'
        })
      } else {
        this.queryParams.pageNo++
        this.getGoodsList()
      }
    },
    goBack() {
      const pageNum = getCurrentPages()
      if (pageNum > 2) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/user/user'
        })
      }
    },
    gotoHome() {
      uni.switchTab({
        url: '/pages/card/card'
      })
    },
    // 格式化价格
    formatPrice(price) {
      if (!price && price !== 0) return '0.00'
      return Number(price).toFixed(2)
    }
  }
};
</script>


<style lang="scss" scoped>
.mallcenter {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

/* 自定义状态栏 */
.custom-status-bar {
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  width: 100%;
}

/* 自定义导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  position: relative;
  z-index: 100;

  .navbar-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    padding: 0 32rpx;

    .navbar-center {
      display: flex;
      align-items: center;
      justify-content: center;

      .navbar-title {
        color: #fff;
        font-size: 36rpx;
        font-weight: 600;
        text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
    }
  }
}

/* 主滚动区域 */
.main-scroll {
  flex: 1;
  height: 0; // 重要：确保滚动容器有固定高度
}

/* 页面内容区域 */
.page-content {
  min-height: 100%;
  padding-bottom: 120rpx; // 为底部tabbar留出空间
}

/* 搜索区域 */
.search-section {
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  padding: 6rpx 32rpx 19rpx 32rpx;
  position: relative;

  .search-container {
    position: relative;
    z-index: 10;
  }

  .search-box {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 50rpx;
    padding: 0 24rpx;
    height: 80rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10rpx);
    transition: all 0.3s ease;

    &:focus-within {
      background: rgba(255, 255, 255, 1);
      box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.15);
      transform: translateY(-2rpx);
    }

    .search-icon {
      margin-right: 16rpx;
      display: flex;
      align-items: center;
    }

    .search-input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      border: none;
      outline: none;

      &::placeholder {
        color: #999;
      }
    }

    .search-clear {
      margin-left: 16rpx;
      display: flex;
      align-items: center;
      padding: 8rpx;
      border-radius: 50%;
      transition: all 0.2s ease;

      &:active {
        background: rgba(0, 0, 0, 0.05);
        transform: scale(0.9);
      }
    }
  }
}

/* 轮播图区域 */
.banner-section {
  margin: 0 32rpx 32rpx;
  margin-top: 30rpx;

  .main-banner {
    height: 320rpx;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.12);

    .banner-img {
      width: 100%;
      height: 100%;
    }
  }
}

/* 商品区域 */
.goods-section {
  /* 区域标题 */
  .section-header {
    padding: 0 32rpx 24rpx;

    .header-content {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .header-title {
        .title-main {
          display: block;
          font-size: 40rpx;
          font-weight: 700;
          color: #2d3436;
          margin-bottom: 8rpx;
        }

        .title-sub {
          display: block;
          font-size: 28rpx;
          color: #636e72;
        }
      }
    }
  }

  /* 商品容器 */
  .goods-container {
    padding: 0 24rpx;
  }

  /* Grid网格 */
  .goods-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    min-height: 500rpx;
  }

  /* 商品卡片 */
  .product-card {
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    position: relative;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    &:active {
      transform: translateY(-4rpx);
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
    }

    /* 图片容器 */
    .card-image-wrapper {
      position: relative;
      width: 100%;
      border-radius: 20rpx 20rpx 0 0;
      overflow: hidden;

      .card-image {
        width: 100%;
        height: 240rpx;
        background: linear-gradient(45deg, #f8f9fa, #e9ecef);
        object-fit: cover;
      }

      /* 优惠券标识 */
      .voucher-badge {
        position: absolute;
        top: 12rpx;
        right: 12rpx;
        background: linear-gradient(135deg, #ff6b35, #ff8c42);
        border-radius: 50rpx;
        padding: 6rpx 12rpx;
        box-shadow: 0 2rpx 8rpx rgba(255, 107, 53, 0.3);

        .badge-text {
          color: #fff;
          font-size: 18rpx;
          font-weight: 600;
        }
      }
    }

    /* 卡片内容 */
    .card-content {
      padding: 20rpx;
      flex: 1;
      display: flex;
      flex-direction: column;

      /* 商品标题 */
      .product-title {
        font-size: 26rpx;
        font-weight: 500;
        color: #333;
        line-height: 1.3;
        margin-bottom: 8rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        overflow: hidden;
        min-height: 68rpx;
      }

      /* 商品简介 */
      .product-brief {
        font-size: 22rpx;
        color: #888;
        line-height: 1.4;
        margin-bottom: 12rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        line-clamp: 1;
        overflow: hidden;
      }

      /* 价格区域 */
      .price-section {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12rpx;

        .current-price {
          display: flex;
          align-items: baseline;

          .price-symbol {
            font-size: 20rpx;
            color: #ff4757;
            font-weight: 500;
            margin-right: 2rpx;
          }

          .price-number {
            font-size: 28rpx;
            color: #ff4757;
            font-weight: 600;
          }
        }

        .sales-info {
          .sales-text {
            font-size: 20rpx;
            color: #999;
            background: #f8f9fa;
            padding: 2rpx 8rpx;
            border-radius: 8rpx;
          }
        }
      }

      /* 卡片底部 */
      .card-footer {
        margin-top: auto;
        
        /* 卖家信息 */
        .seller-info {
          display: flex;
          align-items: center;
          gap: 8rpx;

          .seller-avatar {
            width: 28rpx;
            height: 28rpx;
            border-radius: 50%;
            border: 1rpx solid #eee;
            flex-shrink: 0;
          }

          .seller-name {
            font-size: 20rpx;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
          }
        }
      }
    }
  }

  /* 空状态 */
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 500rpx;

    .empty-icon {
      font-size: 120rpx;
      margin-bottom: 24rpx;
      opacity: 0.6;
    }

    .empty-title {
      font-size: 32rpx;
      color: #636e72;
      font-weight: 500;
      margin-bottom: 12rpx;
    }

    .empty-desc {
      font-size: 28rpx;
      color: #b2bec3;
    }
  }
}

/* 轮播图指示器样式 */
:deep(.uni-swiper-wrapper) {
  border-radius: 20rpx;
}

:deep(.uni-swiper-dots) {
  bottom: 24rpx !important;
}

:deep(.uni-swiper-dot) {
  width: 16rpx !important;
  height: 8rpx !important;
  border-radius: 4rpx !important;
  background: rgba(255, 255, 255, 0.4) !important;
  margin: 0 6rpx !important;
  transition: all 0.3s ease !important;
}

:deep(.uni-swiper-dot-active) {
  width: 32rpx !important;
  background: #fff !important;
}
</style>
